package controllers

import (
	"fmt"
	"html/template"
	"net/url"
	"strings"
	"time"
	"xianzhi/service"
	"xianzhi/utils"
	"xianzhi/utils/wechat"
)

type OrderController struct {
	BaseController
}

func (c *OrderController) Index() {
	userId := c.GetSession("userId")
	p := map[string]interface{}{}
	p["userId"] = userId
	p["convert"] = true
	_, orderList := service.GetOrderList(p)
	c.Data["orderList"] = orderList
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "order/index.html"
}

// 下单
func (c *OrderController) Add() {
	var res *utils.ResJsonStruct
	id := utils.Atoi64(c.GetString("id"))
	if id <= 0 {
		res = utils.ResJson(0, "您还没有选择套餐", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	p := map[string]interface{}{}
	p["id"] = id
	setMeal := service.GetSetMealInfo(p)
	if setMeal.Id <= 0 {
		res = utils.ResJson(0, "套餐异常", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	userId := c.GetSession("userId")
	key := fmt.Sprintf("selected_%d", userId)
	schoolIds := c.GetSession(key)
	schoolIdArr := strings.Split(schoolIds.(string), ",")
	if schoolIds == nil || len(schoolIdArr) < 2 {
		res = utils.ResJson(0, "您还没有进行优选和辅选", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	pushTimeIds := c.GetString("push_time_ids")
	if len(pushTimeIds) <= 0 {
		res = utils.ResJson(0, "您还没有选择推送时间", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	input := url.Values{
		"user_id": {fmt.Sprintf("%d", userId)},
		"set_meal_id": {fmt.Sprintf("%d", id)},
	}
	orderId, err := service.AddOrder(input)
	if err != nil {
		res = utils.ResJson(0, "下单失败，请稍候重试", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	_, err = service.AddOrderSchools(orderId, schoolIds.(string))
	if err != nil {
		res = utils.ResJson(0, "下单失败，请稍候重试", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	_, err = service.AddOrderPushTimes(orderId, pushTimeIds)
	if err != nil {
		res = utils.ResJson(0, "下单失败，请稍候重试", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	go c.SendWechatOrderNotice(orderId)

	res = utils.ResJson(1, "下单成功", "")
	c.Data["json"] = res
	c.ServeJSON()
	return
}

func (c *OrderController) SendWechatOrderNotice(orderId int64) {
	p := map[string]interface{}{}
	p["isReceiveWechatNotice"] = 1
	_, userList := service.GetUserList(p)
	p = map[string]interface{}{}
	p["id"] = orderId
	p["relation"] = true
	order := service.GetOrderInfo(p)
	if order.Id > 0 {
		for _, user := range userList {
			if user.SubscribeStatus == 1 {
				wechat.SendOrderNotice(user.OpenId, "您有新的订单", "", "",
					time.Now().Format("2006-01-02 15:04:05"), "勾选学校",
					fmt.Sprintf("%s %s", order.User.SchoolName, order.User.Phone), "选择套餐", order.SetMealName)
			}
		}
	}
}